package com.gpstracking.Filters;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gpstracking.BE.Usuario;

public class FilterAuth implements Filter{
	
    private FilterConfig filterConfig = null;
    private String attribute = null;	

    private static Pattern excludeUrls = Pattern.compile("^.*/(css|js|images|plugins|servlet)/.*$", Pattern.CASE_INSENSITIVE);
    
    private boolean isWorthyRequest(HttpServletRequest request) {
        String url = request.getRequestURI().toString();
        
        if ( url.contains("login.jsp")) return false;
        
        Matcher m = excludeUrls.matcher(url);

        return (!m.matches());
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
		//System.out.print("Authentication: Request received ...");
		try {
			if ( !isWorthyRequest((HttpServletRequest) request) ) {
				chain.doFilter(request, response);
				return ;
			}
			
			boolean authorized = false;
			if (request instanceof HttpServletRequest) {
				HttpSession session = ((HttpServletRequest)request).getSession(false);
				if (session != null) {
					Usuario user = (Usuario)session.getAttribute("user");
					if(user != null) {
						authorized = true;
					}
				}
			}
			

			if (authorized) {
				chain.doFilter(request, response);
			} else if (filterConfig != null) {
				HttpSession sesion = ((HttpServletRequest) request).getSession(true);
				sesion.setAttribute("url", ((HttpServletRequest) request).getRequestURI());
				
				((HttpServletResponse)response).sendRedirect("/GPSTrackingEE/login.jsp");
				
				/*
				ServletContext context = filterConfig.getServletContext();
				String login_page = context.getInitParameter("loginPage");
				//System.out.print("Authentication: Login page = " + login_page);
				if (login_page != null && !"".equals(login_page)) {
					
					System.out.println(((HttpServletRequest)request).getRequestURI());
					//context.getRequestDispatcher(login_page).forward(request, response);
					
					
					
					
				}*/
			} else { 
				throw new ServletException ("Unauthorized access, unable to forward to login page");
			}
			
		} catch (IOException io) {
			System.out.println("IOException raised in AuthenticationFilter");
		} catch (ServletException se) {
			System.out.println("ServletException raised in AuthenticationFilter");
		}
		
		//System.out.print("Authentication: Response dispatched ...");
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
		 
        this.filterConfig = filterConfig;
        this.attribute = filterConfig.getInitParameter("attribute");
 
        
        
    }

}
